import React,{useEffect} from "react";
import {queryTagInfo} from "@/api/tag.js"
import { Modal, Form, Input, Button } from "antd";
import dialogStyle from "./dialog.module.scss";
import {modifyById,addTag} from "@/api/tag.js"
export default function TagDialog(props) {
  const [form] = Form.useForm();
  const { isOpen, onChange, type,id,getList } = props;
  // console.log(props, "---props");
  
  useEffect(()=>{
    if(id!=-1) {
      getTagInfo(id);
    }
  },[id])

  const getTagInfo = async(id)=>{
     const res =  await queryTagInfo(id);
     console.log("请求",res)
     form.setFieldsValue({
      tagName:res.data.tagName,
     })
  }

  const handleCancel = () => {
    props.onChange();
  };


  const handleFinish = async(value)=>{
    // 进行修改或者添加.
    console.log(value,"ok",id)
    if(type===1) {
      console.log("编辑",value,id)
      await modifyById({tagName:value.tagName,id});
      getList();

    }else {
      console.log("add",value)
      await addTag(value);
      getList();
    }
    form.resetFields();
    props.onChange();
  }
  const handleFinishFailed = ()=>{
    console.error("表单提交错误")
  }
  return (
    <div className="dialog">
      <Modal
        title={type === 1 ? "修改标签" : "新增标签"}
        open={isOpen}
        footer={null}
        onCancel={handleCancel}
        
      >
        <Form onFinish={handleFinish} onFinishFailed={handleFinishFailed} form={form} initialValues={{tagName:""}}>
          <Form.Item
            name="tagName"
            label="标签名"
            rules={[
              {
                whitespace: true,
                type: "string",
                required: true,
                message: "请输入标签名",
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item>
            <div className={dialogStyle['btn-group']}>
              <Button htmlType="reset" className={dialogStyle['ant-btn']} onClick={handleCancel}>取消</Button>
              <Button htmlType="submit" type="primary" className={dialogStyle['ant-btn']}>
                确认
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
